package org.yibinxueyuan.drawcard.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yibinxueyuan.drawcard.entity.Userinfo;
import org.yibinxueyuan.drawcard.mapper.UserInfoMapper;

import java.util.List;

/**
 * 用于测试是否所有框架都正确的整合成功了
 */
@Controller
@RequestMapping(value = "/test")
public class TestFrame {
    @Autowired
    private UserInfoMapper userinfo;

    @RequestMapping(value = {"/","hello3"})
    public String hello3(Model m){
        m.addAttribute("msg","hello,shiro");
        return "test/hello3";
    }

    @RequestMapping(value = "/hello")
    public String hello(Model m){
        m.addAttribute("name","thymeleaf1");
        return "test/hello";
    }
    @RequestMapping(value = "/hello2")
    public String hello2(Model m){
        List<Userinfo> all = userinfo.findAll();
        m.addAttribute("userinfo",all);
        return "test/hello2";
    }

    @RequestMapping(value = "/testlogin")
    public String testlogin(Model m){
        return "test/testlogin";
    }
    @RequestMapping(value = "/login")
    public String login(String username ,String password,Model m){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //执行登录的方法,如果没有异常就是登录成功
        try {
            subject.login(token);
            m.addAttribute("msg","登录成功");
            return "test/hello3";
        }catch (UnknownAccountException e){ //用户不存在
            m.addAttribute("msg","用户名不存在");
            return "test/testlogin";
        }catch (IncorrectCredentialsException e) { //密码错误
            m.addAttribute("msg","密码或用户名错误");
            return "test/testlogin";
        }
    }

    @RequestMapping(value = "/power")
    public String power(){
        return "test/power";
    }

}
